package com.example.springsecurity.security.controller;

import com.example.springsecurity.sms.code.DefaultSmsCodeSender;
import com.example.springsecurity.sms.code.SmsCodeGenerator;
import com.example.springsecurity.sms.code.ValidateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 创建一个接口用于生成验证，此接口会向外暴漏出来，不被Spring Seurity过滤器拦截，
 * 下文会写详细的Spring Seurity配置。接口内生成验证码，并且作为key-value键值对保存在session中，最后向手机号发送验证码
 */
@RestController
public class ValidateCodeController {
    @Autowired
    private SmsCodeGenerator smsCodeGenerator;
    @Autowired
    private DefaultSmsCodeSender defaultSmsCodeSender;

    @GetMapping("/code/sms")
    public String createSmsCode(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestParam String mobile) throws IOException {

        //获取验证码
        ValidateCode smsCode = smsCodeGenerator.generate(new ServletWebRequest(request));
        //把验证码设置到session
        session.setAttribute(mobile, smsCode);
        //验证码打印控制台
        defaultSmsCodeSender.send(mobile,smsCode.getCode());
        return "验证码是 : " + smsCode.getCode();
    }

}
